package cn.zwx.common.logger.utils;

import com.google.gson.*;
import org.springframework.web.multipart.MultipartFile;

import java.lang.reflect.Type;
import java.util.Objects;

/**
 * Json工具类
 * 因为FastJson在json复杂数据结构时会报错 比如MultipartFile
 * @see:cn.wywk.logger.utils
 * @author:zhangwenxue
 * @createTime:2022/2/15 10:54
 * @version:1.0
 */
public class JsonForGSonUtil {
    private static Gson gson = null;
    //判断gSon对象是否存在了,不存在则创建对象
    static {
        gson= new GsonBuilder().setLongSerializationPolicy(LongSerializationPolicy.STRING)
                .enableComplexMapKeySerialization().setExclusionStrategies(new ExclusionStrategy() {
                    @Override
                    public boolean shouldSkipField(FieldAttributes fieldAttributes) {
                        Type declaredType = fieldAttributes.getDeclaredType();
                        String typeName = MultipartFile.class.getTypeName();
                        return Objects.equals(typeName,declaredType.getTypeName());
                    }

                    @Override
                    public boolean shouldSkipClass(Class<?> aClass) {
                        return Objects.equals(aClass,MultipartFile.class);
                    }
                }).create();
    }
    //无参的私有构造方法
    private JsonForGSonUtil() {
    }

    /**
     * 将对象转成json格式
     * @param obj 转换对象
     * @return String
     */
    public static String beanToJson(Object obj) {
        String str = null;
        if (gson != null) {
            str = gson.toJson(obj);
        }
        return str;
    }

    /**
     *  将json转成特定的cls的对象
     * @param str json字符串
     * @param cls 对象
     * @return T 返回对象
     * @author zhangwenxue
     * @createTime 2022/2/15 10:59
     **/
    public static <T> T jsonToBean(String str, Class<T> cls) {
        T t = null;
        if (gson != null) {
            //传入json对象和对象类型,将json转成对象
            t = gson.fromJson(str, cls);
        }
        return t;
    }




}
